package chapter.third.item9;

/**
 * 
 * @author lzy
 *
 */
public class PhoneNumber implements Cloneable,Comparable<PhoneNumber>{
	private final short areaCode;
	private final short prefix;
	private final short lineNumber;
	
	private volatile int hashCode;
	
	public PhoneNumber(short areaCode, short prefix, short lineNumber) {
		rangeChack(areaCode,999,"area code");
		rangeChack(prefix,999,"prefix");
		rangeChack(lineNumber,9999,"line number");
		this.areaCode = areaCode;
		this.prefix = prefix;
		this.lineNumber = lineNumber;
	}
	
	private void rangeChack(short val, int max, String s) {
		if(val<0||val>max){
			throw new IllegalArgumentException("field:"+s);
		}
	}

	@Override
	public boolean equals(Object obj) {
		if(obj==this){
			return true;
		}
		if(!(obj instanceof PhoneNumber))
			return false;
		PhoneNumber pn = (PhoneNumber)obj;
		return pn.areaCode==areaCode&&
				pn.prefix==prefix&&
				pn.lineNumber==lineNumber;
	}

	@Override
	public int hashCode() {
		int result = hashCode;
		if(result==0){
			result = 17;
			result = 31*result+areaCode;
			result = 31*result+prefix;
			result = 31*result+lineNumber;
			hashCode = result;
		}
		return result;
	}
	
	
	
	@Override
	public String toString() {
		return "[PhoneNumber(areaCode:"+areaCode+",prefix:"+prefix+",lineNumber:"+lineNumber+")]";
	}
	
	

	@Override
	protected PhoneNumber clone() throws CloneNotSupportedException {
		return (PhoneNumber)super.clone();
	}

	public static void main(String[] args) throws CloneNotSupportedException {
		PhoneNumber pn = new PhoneNumber((short)86,(short)421,(short)1234);
		int hash = pn.hashCode();
		System.out.println(pn.toString()+"散列码:"+hash);
		PhoneNumber pn1 = pn.clone();
		System.out.println(pn1);
	}

	public int compareTo(PhoneNumber o) {
		int areaCodeDiff = areaCode-o.areaCode;
		if(areaCodeDiff!=0)
			return areaCodeDiff;
		int prefixDiff = prefix-o.prefix;
		if(prefixDiff!=0) 
			return prefixDiff;
		return lineNumber-o.lineNumber;
	}
	
	
	
	
	
}
